package com.hzt.agprosaleplatform.service.impl;

import com.hzt.agprosaleplatform.entity.FinanceApplication;
import com.hzt.agprosaleplatform.mapper.FinanceApplicationMapper;
import com.hzt.agprosaleplatform.service.FinanceApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FinanceApplicationServiceImpl implements FinanceApplicationService {

    @Autowired
    private FinanceApplicationMapper mapper;

    @Override
    public FinanceApplication createApplication(FinanceApplication application) {
        if (application.getApplyTime() == null) {
            application.setApplyTime(new Date());
        }
        //application.setStatus(FinanceApplication.STATUS_PENDING);

        // 3. 其他可选：设置审计相关字段为null（后端控制，前端无需传递）
        application.setStatus(0);
        application.setAuditTime(null);
        application.setAuditOpinion(null);

        mapper.insert(application);
        return application;
    }

    @Override
    public FinanceApplication getApplicationById(Integer financeId) {
        return mapper.selectById(financeId);
    }

    @Override
    public List<FinanceApplication> getApplicationsByUserId(String userId) {
        return mapper.selectByUserId(userId);
    }

    @Override
    public List<FinanceApplication> getApplicationsByStatus(Integer status) {
        return mapper.selectByStatus(status);
    }

    @Override
    public boolean updateApplicationStatus(Integer financeId, Integer status, String auditOpinion) {
        return mapper.updateStatus(financeId, status, new Date(), auditOpinion) > 0;
    }

    @Override
    public boolean approveApplication(Integer financeId, String auditOpinion) {
        return updateApplicationStatus(financeId, FinanceApplication.STATUS_APPROVED, auditOpinion);
    }

    @Override
    public boolean rejectApplication(Integer financeId, String auditOpinion) {
        return updateApplicationStatus(financeId, FinanceApplication.STATUS_REJECTED, auditOpinion);
    }

    @Override
    public boolean cancelApplication(Integer financeId, String cancelReason) {
        // 1. 校验申请是否存在
        FinanceApplication application = mapper.selectById(financeId);
        if (application == null) {
            throw new RuntimeException("融资申请不存在");
        }

        // 2. 校验状态：仅"待审核"（0）可取消
        if (application.getStatus() != FinanceApplication.STATUS_PENDING) {
            throw new RuntimeException("仅待审核的申请可取消，当前状态：" + getStatusText(application.getStatus()));
        }

        // 3. 更新状态为"已取消"（6），并记录取消时间和原因
        int rows = mapper.updateStatus(
                financeId,
                FinanceApplication.STATUS_CANCELED,  // 状态改为已取消
                new Date(),  // 取消时间（audit_time字段复用）
                "用户主动取消：" + cancelReason  // 取消原因（audit_opinion字段复用）
        );

        // 4. 返回是否更新成功（影响行数>0则成功）
        return rows > 0;
    }

    // 辅助方法：根据状态获取文本（可选，也可放工具类）
    private String getStatusText(Integer status) {
        Map<Integer, String> statusMap = new HashMap<>();
        statusMap.put(0, "待审核");
        statusMap.put(1, "审核通过");
        statusMap.put(2, "审核拒绝");
        statusMap.put(3, "已放款");
        statusMap.put(4, "已还款");
        statusMap.put(5, "逾期");
        statusMap.put(6, "已取消");
        return statusMap.getOrDefault(status, "未知状态");
    }
}
